﻿using FirstDemo.Config;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace FirstDemo.Controllers
{
    [Route("api/[controller]")]
    public class AuthController : Controller
    {
        private JwtConfig jwtconfig;
        public AuthController(IOptions<JwtConfig> option)
        {
            jwtconfig = option.Value;
        }

        /// <summary>
        /// 获得Token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Get()
        {
            var claim = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Jti,"1"),//编号
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),//签发时间
                new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),//生效时间
                // 过期时间 100秒
                //new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(100)).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Iss,"Lesan"), // 签发者
                new Claim(JwtRegisteredClaimNames.Aud,"User") // 接收者
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtconfig.SigningKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: jwtconfig.Issuer,
                audience: jwtconfig.Audience,
                claims: claim,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);

            HttpContext.Session.SetString("Token", new JwtSecurityTokenHandler().WriteToken(token));
            return Ok(new JwtSecurityTokenHandler().WriteToken(token));
        }

        //在访问需要JWT身份认证的接口时，接口添加header参数Authorization，值为“Bearer”+空格+token。
        //若不能通过JWT身份认证，则调用接口返回状态401未认证。
        /// <summary>
        /// 在需要身份认证的方法添加[Authorize]
        /// </summary>
        [Authorize]
        [HttpGet("testAuth")]
        public JsonResult testAuth()
        {
            return Json("Token: " + HttpContext.Session.GetString("Token"));
            //return Json(new ResultModel(Response.StatusCode));

        }
    }
}
